package com.hbnu.gui.controller;

import com.hbnu.common.factory.ServiceFactory;
import com.hbnu.common.response.ServiceResponse;
import com.hbnu.common.service.RegisterService;

import com.hbnu.common.util.CheckUtil;
import com.hbnu.gui.constant.Views;
import com.hbnu.gui.util.AlertUtil;
import com.hbnu.gui.util.WindowManager;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RegisterController {
    @FXML
    private TextField usernameInput;
    @FXML
    private PasswordField passwordInput;
    @FXML
    private PasswordField confirmPasswordInput;
    @FXML
    private Button registerBtn;
    @FXML
    private Button backToLoginBtn;

    private final Logger logger = LoggerFactory.getLogger(RegisterController.class);
    private final WindowManager windowManager = WindowManager.getInstance();
    private final RegisterService registerService = ServiceFactory.getRegisterService();

    @FXML
    public void registerButtonClicked() {
        String username = usernameInput.getText().trim();
        String errorMessage = CheckUtil.checkUsername(username);

        if (errorMessage != null) {
            AlertUtil.showAlert(Alert.AlertType.ERROR, "注册失败", errorMessage);
            return;
        }

        String password = passwordInput.getText().trim();
        errorMessage = CheckUtil.checkPassword(password);

        if (errorMessage != null) {
            AlertUtil.showAlert(Alert.AlertType.ERROR, "注册失败", errorMessage);
            return;
        }

        String confirmPassword = confirmPasswordInput.getText().trim();
        if (!password.equals(confirmPassword)) {
            AlertUtil.showAlert(Alert.AlertType.ERROR, "注册失败", "密码不一致！");
            return;
        }

        logger.info("收到注册请求：用户名={}", username);
        ServiceResponse<Void> response = registerService.handleRegister(username, password);

        if (response.isSuccess()) {
            logger.info("注册成功：用户名={}", username);
            AlertUtil.showAlert(Alert.AlertType.INFORMATION, "注册成功", response.getAlertMessage());
            clearInput();
        } else {
            logger.error("注册失败：用户名={}，原因={}", username, response.getErrorMessage());
            AlertUtil.showAlert(Alert.AlertType.ERROR, "注册失败", response.getErrorMessage());
        }
    }

    @FXML
    public void backToLoginButtonClicked() {
        windowManager.closeView(Views.REGISTER);
        windowManager.showView(Views.LOGIN);
    }

    private void clearInput() {
        usernameInput.clear();
        passwordInput.clear();
        confirmPasswordInput.clear();
    }
}
